# set -x

# 每日构建SDK  https://ci.openharmony.cn/workbench/cicd/dailybuild/dailylist
SDK_URL="https://cidownload.openharmony.cn/version/Master_Version/OpenHarmony_5.0.2.50/20241104_021208/version-Master_Version-OpenHarmony_5.0.2.50-20241104_021208-ohos-sdk-public.tar.gz"

ROOT_DIR=$(pwd)
PRJ_DIR=
PRJ_NAME=
EXAMPLE_NAME=
WORK_DIR=$(pwd)/RN_Work
# TESTERINO_PATH=$(pwd)/cicd/rn/rnoh-testerino-0.0.9.tgz
SHELL_DIR=$(pwd)/cicd/rn

TOOLS_DIR="$WORK_DIR/command-line-tools"
PREBUILD_DIR="$WORK_DIR/rnoh_prebuild"

OUT_DIR=$ROOT_DIR/out/tpc
NODE_HOME=$WORK_DIR/command-line-tools/tool/node/bin

# 打印当前文件结构
function check_files() {
	# 检查三方库目录是否预热成功
	echo "检查三方库目录是否预热成功"
	ls -al
	ls -al ./

	rm -rf ~/.hvigor/

	# 检查 WORK_DIR 目录
	mkdir -p "$WORK_DIR"
	ls -al "$WORK_DIR/"
	
	cd "$WORK_DIR"
	if [ $? -ne 0 ]; then
	    echo "$WORK_DIR 不存在!!!"
        return 1
	fi
}

function prepare_rnoh_prebuild() {
		
	cd  $WORK_DIR
	echo "start prepare build $(pwd)"
	
    if [ -d "rnoh_prebuild" ]; then
	    cd rnoh_prebuild
		git fetch origin
		git reset --hard origin/master
		cd ..
	else
		git clone https://gitee.com/jarayard/rnoh_prebuild.git --depth 1
		if [ $? -ne 0 ]; then
			echo "Warning: git clone rnoh_prebuild failed! Start retry!!!"
			rm -rf "$PREBUILD_DIR"/
			git clone https://gitee.com/jarayard/rnoh_prebuild.git --depth 1
			if [ $? -ne 0 ]; then
			    rm -rf "$PREBUILD_DIR"/
				echo "Error: git clone rnoh_prebuild failed!!!"
			    return 1
			fi
		fi
	fi
	echo "The rnoh_prebuild path already exists"
	

}

# 准备SDK
function prepare_sdk() {
    echo "准备 SDK"
    cd "$WORK_DIR"
	
	#  mkdir -p "$TOOLS_DIR"/
	rm -rf OHOS_SDK* && mkdir -p OHOS_SDK/sdk/ && cd OHOS_SDK
	
	git clone https://gitee.com/jarayard/command-line-tools_sdk-01234.git --depth 1
	if [ $? -ne 0 ]; then

		echo "[Warning]: 下载失败，重试!!!"

		rm -rf "$WORK_DIR"/command-line-tools_sdk-01234/
		git clone https://gitee.com/jarayard/command-line-tools_sdk-01234.git --depth 1

		if [ $? -ne 0 ]; then
			echo "[Error]: 下载失败!!!"
			return 1
		fi
	fi

	cp ./command-line-tools_sdk-01234/sdk_part_00* ./sdk/
	
	git clone https://gitee.com/jarayard/command-line-tools_sdk-567.git --depth 1
	if [ $? -ne 0 ]; then
		echo "[Warning]: 下载失败，重试!!!"

		rm -rf "$WORK_DIR/command-line-tools_sdk-567/"
		git clone https://gitee.com/jarayard/command-line-tools_sdk-567.git --depth 1
		if [ $? -ne 0 ]; then
		    echo "[Error]: 下载失败!!!"
			return 1
		fi
	fi

	echo "[Success]: 下载完成!!!"
	cp ./command-line-tools_sdk-567/sdk_part_00* ./sdk/
	
	echo "开始解压 SDK"
	cd sdk
	cat sdk_part_00* > sdk.tar.xz
	tar -xJf sdk.tar.xz

	if [ $? -ne 0 ]; then
		echo "[Error]: 解压失败!!!"
		return 1
	fi
	echo "[Success]: 解压完成!!!"

	ls ./sdk/default/
	
	mv ./sdk/ "$TOOLS_DIR/"
	
	# ===================================================================================================================
	
	echo "开始下载每日构建 SDK"
	curl -f -L -- "$SDK_URL" > sdk_openharmony.tar.gz
	if [ $? -ne 0 ]; then
		echo "[Error]: 下载失败!!!"
		return 1
	fi
	echo "[Success]: 下载完成!!!"

	echo "开始校验 SDK"
	local correct_SHA256="ec97fd493865221618654d74bb535b27fe7cb1cf0deb03a0fe316fe1e3a9d532"
	local sdk_sum=`sha256sum sdk_openharmony.tar.gz`
	sdk_sum=${sdk_sum:0:64}  # SHA-256 产生64个字符的哈希值
	if [ "x$sdk_sum" != "x$correct_SHA256" ]
	then
		echo "tools_sum(no x) is : x$sdk_sum"
		echo "SHA-256_command-line-tools(no x) is : x$correct_SHA256"
		echo "Error: please change sdk_openharmony.tar.gz!!!"
		return 1
	fi
	echo "[Success]: SDK 校验正确!!!"


	echo "开始解压每日构建 SDK"
	tar -zxvf ./sdk_openharmony.tar.gz
	cd ./linux
	if [ $? -ne 0 ]; then
		echo "[Error]: 未找到 linux 目录!!!"
		return 1
	fi
	
	for file in `ls ./`
	do
		unzip -qo "$file"
		if [ $? -ne 0 ]; then
			echo "[Error]: $file 解压失败!!!"
		    return 1
	    fi
		rm -f "$file"
		echo "[Success]: $file 解压完成!!!"
	done
	echo "[Success]: 每日构建 SDK 解压完成!!!"
	
	mkdir -p "$TOOLS_DIR/sdk/default/openharmony/"
	mv ./ets/ ./js/ ./native/ ./previewer/ ./toolchains/ "$TOOLS_DIR/sdk/default/openharmony/"
	
	# ===================================================================================================================

	echo "[Success]: SDK 准备完成!!!"
	
	rm -rf "$WORK_DIR/OHOS_SDK*"
    return 0
}

# 准备command-line-tools
function prepare_tools() {
    # 本地调试时，在此直接return 0，手动解压command-line-tools到RN_Work
    # return 0
	
    echo "start prepare command-line-tools"
	
	rm -rf "$TOOLS_DIR"/
	
	mv "$PREBUILD_DIR"/command-line-tools/ "$WORK_DIR"/
	
	cd "$TOOLS_DIR"/
	for file in `ls ./*.tar.xz`
	do
	    tar -xJf "$file"
		if [ $? -ne 0 -a $? -ne 1 ]; then
			echo "Failed to extract file $file!!!"
			return 1
		fi
		echo "Unzipped $file successfully!!!"
		rm -f "$file"
	done

    echo "The command-line-tools is ready, except for the sdk"
	
	# ===================================================================================================================
	
	prepare_sdk
	if [ $? -ne 0 ]; then
		echo "Failed to extract prepare_sdk()!!!"
		return 1
	fi

    echo "The command-line-tools is ready, including the sdk"

    return 0
}

function prepare_config_files() {
    echo "start prepare config_files"

	# cp "$PREBUILD_DIR"/config_files/npm/.npmrc ~/
	cp "$SHELL_DIR"/.npmrc ~/
	if [ $? -ne 0 ]; then
        echo "Failed to copy npmrc!!!"
        return 1
    fi

	rm -rf ~/.ohpm/ && mkdir ~/.ohpm/
    cp "$PREBUILD_DIR"/config_files/ohpm/.ohpmrc ~/.ohpm/
	if [ $? -ne 0 ]; then
        echo "Failed to copy .ohpmrc!!!"
        return 1
    fi
	echo ".npmrc and .ohpmrc already exists"

    # sleep 3  # 暂停3秒，用于调试
	
    return 0
}

function download_diff() {
    local pr_num=$1
    local token="dwCzGQf1Wy9oKTfvezoT7C7x"
    local url="https://api.gitcode.com/api/v5/repos/openharmony-sig/$PRJ_NAME/pulls/$pr_num/diff"

    curl --location \
    $url \
    --header 'PRIVATE-TOKEN: dwCzGQf1Wy9oKTfvezoT7C7x' \
    -o $pr_num.diff

    if [ $? -ne 0 ]
    then
        echo "curl failed!"
        return 1
    fi
    return 0
}

function get_project_name() {
    echo "start get_project_name! get $1"

    local pr_name=$1
    pr_name=${pr_name#*openharmony-sig/}
	PRJ_NAME=${pr_name%/*/*}

	echo "PRJ_NAME:$PRJ_NAME"

	local PROJECT=$(get_project_path $1)

	PRJ_DIR=$ROOT_DIR/$PRJ_NAME/$PROJECT

	echo "PRJ_DIR:$PRJ_DIR"
	echo "$pwd"
	if [ ! -d $PRJ_DIR ]; then
		echo "Error: Cannot find $PRJ_DIR!!!"
		return 1
	else
		getExamplePath $PRJ_DIR
		if [ $? -ne 0 ]; then
			echo "Error: Cannot find $EXAMPLE_NAME!!!"
			return 1
		fi
	fi
}

function get_project_path() {
    DEFALUT_PROJECT='packages/multidevice_layout'
    local diff_url=$1
    local pr_num=${diff_url##*/}
    local diff_name=$pr_num.diff
    local retval=1
    local compont_name=
    if [ ! -f $diff_name ]
    then
        download_diff $pr_num
        if [ $? -ne 0 ]
        then
            echo "download $diff_name failed!"
            return $retval
        fi
    fi
    local diff_str=`cat $diff_name | grep "diff --git"`

    for diff in $diff_str
    do
        local tmp=`echo $diff | grep "/"`
        if [ ! -z "$tmp" ]
        then
            local find=0
            readarray -t dir_array <<< "$(echo "$tmp" | tr '/' '\n')"
            length=${#dir_array[@]}
            if (( length >= 3 )) && [[ "${dir_array[1]}" == "packages" ]]; then
                echo "${dir_array[1]}/${dir_array[2]}"
                retval=0
                find=1
                break
            fi
        fi
    done
    if [[ $find -eq 0 ]]
    then
        echo "$DEFALUT_PROJECT"
    fi
    return $retval
}

function prepare_project() {
    echo "start prepare project! get $1"
	
    get_project_name $1
	if [ $? -ne 0 ]; then
		echo "Error: Cannot get_project_name"
		return 1
	fi

	# 检查api
	check_sdk_whith_apiversion

	
    return 0
}
function getExamplePath() {
    echo "start EXAMPLE_NAME! get $1"
	local pr_name=$1
	local ex_name=""
	local result=1

	ex_name=${pr_name}/example
	result=0
	
	export EXAMPLE_NAME=$ex_name
    	echo "EXAMPLE_NAME=$EXAMPLE_NAME"
		cd $EXAMPLE_NAME
		# cp $TESTERINO_PATH rnoh-testerino-0.0.9.tgz

	return $result

}
function install_project() {
    get_project_name $1
	if [ $? -ne 0 ]; then
		echo "Error: Cannot get_project_name"
		return 1
	fi

	# 安装项目依赖
	# cd $PRJ_DIR
	# npm i --legacy-peer-deps
	# npm pack
	
	# 安装example依赖
	cd $EXAMPLE_NAME
	# npm i --legacy-peer-deps
	# # npm run install:pkg
	# npm run dev
	npm run fast:pkg

	# 安装ohpm 依赖
	cd $EXAMPLE_NAME/Music
	echo "cd $EXAMPLE_NAME/Music"
	ohpm install

	return 0

}

function check_sdk_whith_apiversion() {
    cd $EXAMPLE_NAME/Music
	if [ $? -ne 0 ]; then
		echo "Error: Cannot find Music project!!!"
		return 1
	fi
	echo "The Music project path already exists"
	cp build-profile.template.json5 build-profile.json5
    local tmpVersion=`cat build-profile.json5 | grep compileSdkVersion`
    # echo "$tmpVersion"
    local ret=1
	local tmpVer=`echo "${tmpVersion}" | grep "13"`
	if [ ! -z "${tmpVer}" ]
	then
		# echo "tmpVer=$tmpVer"
		ret=0
	else
		echo "get SDK version failed! compileSdkVersion is ${tmpVersion}"
	fi

    return $ret
}

function check_tools_env() {

	# 配置环境变量
	export PATH="$WORK_DIR"/command-line-tools/bin:"$WORK_DIR"/command-line-tools/tool/node/bin:$PATH
	export DEVECO_SDK_HOME=$WORK_DIR/command-line-tools/sdk

	echo "开始环境监测!!!"
		# echo "环境变量：$PATH"
	echo "DEVECO_SDK_HOME: $DEVECO_SDK_HOME"

	node -v
	npm -v
	
	export npm_config_loglevel=error
	
	npm install --save-dev yarn
	yarn -v

	ohpm -v
	# echo "$ hvigorw -v"
	# hvigorw -v

}

# 清空并创建新目录
function check_dir() {
  echo "[INFO] Empty and create the directory: $1"
  if [ -d "$1" ]
  then
    rm -rf "$1/"
  fi
  mkdir -p "$1"
}

# 编译ohpm模块，生成har包（Debug模式）
function assemble_hap() {
  echo "[INFO] Start to make module '$1'"
  cd $EXAMPLE_NAME/Music
  # 编译模块
  hvigorw clean
  # 如果不加 --no-daemon 选项，有时候会报错。命令行模式下推荐使用此参数。
	hvigorw assembleHap --mode module -p module=$1@default -p product=default -p buildMode=debug -p debuggable=true --no-daemon
  if [ $? -ne 0 ]; then
    echo "[ERROR] Failed to make module '$1'"
    return 1
  fi
	echo "[SUCCESS] Make module '$1' successfully"
	echo "[SUCCESS] Make $OUT_DIR $PRJ_DIR.hap successfully"
  # 归档产物
  cp "./$1/build/default/outputs/default/$1-default-unsigned.hap" $OUT_DIR/$PRJ_NAME.hap
  return 0
}